package com.klhappy.houyuan.utils;

import java.util.HashMap;

/**
 * 远距离调用方法
 *
 */
public class NotifyMethod {

    public HashMap<String, Observer> keymap;

    private static class NotificationCenterHolder {

        private static NotifyMethod holder = init();

        private static NotifyMethod init() {
            NotifyMethod notificationCenter = new NotifyMethod();
            notificationCenter.keymap = new HashMap<String, Observer>();
            return notificationCenter;
        }

    }

    public static NotifyMethod getInstance() {
        return NotificationCenterHolder.holder;
    }

    private class Observer {
        public NotifyListener listener;

        public Observer(NotifyListener listener) {
            this.listener = listener;
        }
    }

    public void postNotification(String keyPath) {
        this.postNotification(keyPath, null);
    }

    public void postNotification(String keyPath, Object object) {
        Observer observer = keymap.get(keyPath);
        if(observer == null) {
            return;
        }
        NotifyListener listener = observer.listener;
        if (null != listener) {
            try {
                listener.notify(object);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public void addObserver(String keyPath, NotifyListener listener) {
        keymap.put(keyPath, new Observer(listener));
    }


    public void removeObserver(String keyPath) {
        keymap.remove(keyPath);
    }

    public interface NotifyListener {
        void notify(Object o);
    }

}
